package com.itboye.jigongbao.activity

import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.widget.AbsListView
import android.widget.AdapterView
import android.widget.ImageView
import com.itboye.jigongbao.R
import com.itboye.jigongbao.adpapter.NotifyMessageAdapter
import com.itboye.jigongbao.app.MyApplication
import com.itboye.jigongbao.base.BaseActivity
import com.itboye.jigongbao.bean.JiYiBiBean
import com.itboye.jigongbao.bean.NotifyMessageBean
import com.itboye.jigongbao.enums.DetailEnums
import com.itboye.jigongbao.retrofit.base.ResultEntity
import com.itboye.jigongbao.retrofit.presenter.UserPrestener
import com.itboye.jigongbao.utils.ByJsonUtils.Companion.parseJson
import com.itboye.jigongbao.utils.Const
import com.itboye.jigongbao.utils.SPUtils
import com.itboye.jigongbao.utils.TitleBarUtils
import com.itboye.jigongbao.utils.ToastUtil.ByAlert
import com.itboye.jigongbao.widget.SureDeleteDialog
import com.itboye.jigongbao.widget.swipemenulistview.SwipeMenuCreator
import com.itboye.jigongbao.widget.swipemenulistview.SwipeMenuItem
import com.itboye.jigongbao.widget.xlistview.XListView
import kotlinx.android.synthetic.main.activity_notify_message.*
import org.json.JSONObject
import java.io.Serializable
import java.util.*
import kotlin.collections.ArrayList

class NotifyMessageActivity : BaseActivity(), Observer {
    var iv_actionbar_left: ImageView? = null
    var ar: ArrayList<NotifyMessageBean>? = null
    override fun update(p0: Observable?, p1: Any?) {
        lv_notifymessage.stopLoadMore()
        lv_notifymessage.stopRefresh()
//        ptr_notifymessage_list_framelayout.refreshComplete()
        var entity = p1 as ResultEntity
        if (entity.code != 0) {
            ByAlert.alert(entity.msg)
        } else {
            if (entity.eventType == UserPrestener.By_Message_query_Success) {
                if (pageIndex == 1) {
                    ar?.clear()
                }
                ar?.addAll(entity.data as ArrayList<NotifyMessageBean>)
                adapter!!.notifyDataSetChanged()
            } else if (entity.eventType == UserPrestener.By_Message_query_Fail) {
                ByAlert.alert(entity.msg)
            } else if (entity.eventType == UserPrestener.By_Message_info_Success) {
                var model = entity.data as NotifyMessageBean
                var extra: JSONObject? = null
                var item_id = ""
                try {
                    extra = JSONObject(model.extra)
                    if (extra.has("type")) {
                        extra.getString("type")
                    }
                    if (extra.has("item_id")) {
                        item_id = extra.getString("item_id")
                    }
                } catch (e: Exception) {

                }
                //通过项目id查询项目详情
                userPrestener?.By_JgbRecord_info(item_id, NotifyMessageActivity@ this)

            } else if (entity.eventType == UserPrestener.By_Message_info_Fail) {
                ByAlert.alert(entity.msg)
            } else if (entity.eventType == UserPrestener.By_JgbRecord_info_Success) {
                var model = entity.data as JiYiBiBean.JiYiBiEntity
                var intent = Intent(NotifyMessageActivity@ this, HeZhangDetailActivity::class.java)
                intent.putExtra("shenhe", true)
                intent.putExtra("title", "明细")
                intent.putExtra("model", model as Serializable)
                if (model.item_type_key == "00S002003") {
                    intent.putExtra("type", if (role == Const.FORCEMAN)
                        DetailEnums.YIJIBI_FOREMAN_DIANGONG
                    else
                        DetailEnums.YIJIBI_WORKER_DIANGONG
                    )
                }
                if (model.item_type_key == "00S002002") {
                    intent.putExtra("type", if (role == Const.FORCEMAN)
                        DetailEnums.YIJIBI_FOREMAN_BAOGONG
                    else
                        DetailEnums.YIJIBI_WORKER_BAOGONG
                    )
                }
                if (model.item_type_key == "00S002004") {
                    intent.putExtra("type", if (role == Const.FORCEMAN)
                        DetailEnums.YIJIBI_FOREMAN_JIEZHI
                    else
                        DetailEnums.YIJIBI_WORKER_JIEZHI
                    )
                }
                if (model.item_type_key == "00S002005") {
                    intent.putExtra("type", if (role == Const.FORCEMAN)
                        DetailEnums.YIJIBI_FOREMAN_JIESUAN
                    else
                        DetailEnums.YIJIBI_WORKER_JIESUAN
                    )
                }
                startActivity(intent)
            } else if (entity.eventType == UserPrestener.By_JgbRecord_info_Fail) {
                ByAlert.alert(entity.msg)
            } else if (entity.eventType == UserPrestener.By_Message_del_Success) {
                ByAlert.alert(entity.msg)
                query()
            } else if (entity.eventType == UserPrestener.By_Message_del_Fail) {
                ByAlert.alert(entity.msg)
            }

        }
    }

    var userPrestener: UserPrestener? = null
    var role = ""
    override fun getLayoutId(): Int {
        return R.layout.activity_notify_message
    }

    var pageIndex = 1
    private var adapter: NotifyMessageAdapter? = null

    internal var isAtTop = true
    internal var isAtBottom = false
    override fun initData() {
        TitleBarUtils().initTitlebarStyle1(this, trans_action_bar_notifymessage, "消息", R.drawable.img_back, "", 0, "")
        role = SPUtils.getSp(Const.ROLE).toString()
//        BasePtr.setPagedPtrStyle(ptr_notifymessage_list_framelayout)
        userPrestener = UserPrestener(this)
        ar = ArrayList()
        adapter = NotifyMessageAdapter(this, ar!!, R.layout.item_notify_message)
        lv_notifymessage.adapter = adapter
        lv_notifymessage.setOnItemClickListener({ adapterView: AdapterView<*>, view1: View, i: Int, l: Long ->
            var model=ar!![i - 1]
            var msg_status = model.msg_status
            if (msg_status == 1) {
                //已读
                //通过项目id查询项目详情
                var item_id = parseJson(model.extra!!, "item_id").toString()
                userPrestener?.By_JgbRecord_info(item_id, NotifyMessageActivity@ this)
            } else {
                //未读
                //先获取详情
                userPrestener!!.By_Message_info(MyApplication.instance?.loginInfo?.getUid().toString(), model.id, NotifyMessageActivity@ this)
            }


        })
        lv_notifymessage.setPullRefreshEnable(true)
        lv_notifymessage.setPullLoadEnable(true)
        lv_notifymessage.setXListViewListener(object : XListView.IXListViewListener {

            override fun onRefresh() {
                pageIndex = 1
                query()
            }

            override fun onLoadMore() {
                pageIndex++
                query()
            }

        })
//        ptr_notifymessage_list_framelayout.setPtrHandler(object : PtrHandler2 {
//            override fun onRefreshBegin(frame: PtrFrameLayout?) {
//                pageIndex = 1
//                query()
//            }
//
//            override fun onLoadMoreBegin(frame: PtrFrameLayout?) {
//                pageIndex++
//                query()
//            }
//
//            override fun checkCanDoRefresh(frame: PtrFrameLayout?, content: View?, header: View?): Boolean {
//                return isAtTop
//            }
//
//            override fun checkCanDoLoadMore(frame: PtrFrameLayout?, content: View?, footer: View?): Boolean {
//                return isAtBottom
//            }
//
//        })
        lv_notifymessage!!.setOnScrollListener(object : AbsListView.OnScrollListener {
            override fun onScroll(p0: AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
                if (firstVisibleItem == 0) {
                    val firstVisibleItemView = lv_notifymessage!!.getChildAt(0)
                    if (firstVisibleItemView != null && firstVisibleItemView!!.getTop() == 0) {
                        isAtTop = true
                        isAtBottom = false
                        Log.d("ListView", "##### 滚动到顶部 #####")
                    } else {
                        isAtTop = false
                    }
                } else if (firstVisibleItem + visibleItemCount == totalItemCount) {
                    val lastVisibleItemView = lv_notifymessage!!.getChildAt(lv_notifymessage!!.getChildCount() - 1)
                    if (lastVisibleItemView != null && lastVisibleItemView!!.getBottom() == lv_notifymessage!!.getHeight()) {
                        Log.d("ListView", "##### 滚动到底部 ######")
                        isAtTop = false
                        isAtBottom = true
                    } else {
                        isAtBottom = false
                    }
                }
            }

            override fun onScrollStateChanged(p0: AbsListView?, p1: Int) {

            }

        })
        initSwipListView()
    }

//    private var mDownX: Float = 0f
//    private var mDownY: Float = 0f
//    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
//        when (ev!!.action) {
//            MotionEvent.ACTION_DOWN -> {
//                mDownX = ev.getX()
//                mDownY = ev.getY()
//                lv_notifymessage.requestDisallowInterceptTouchEvent(true)
//                ptr_notifymessage_list_framelayout.setEnabled(false)
//            }
//            MotionEvent.ACTION_MOVE -> {
//                var moveX = ev.getX()
//                var moveY = ev.getY()
//                //ViewPager滑动
//                if (Math.abs(moveX - mDownX) > Math.abs(moveY - mDownY)) {
//                    lv_notifymessage.requestDisallowInterceptTouchEvent(true)
//                    ptr_notifymessage_list_framelayout.setEnabled(false)
//                    //ListView滑动
//                } else {
//                    lv_notifymessage.requestDisallowInterceptTouchEvent(false)
//                    ptr_notifymessage_list_framelayout.setEnabled(true)
//                }
//                mDownX = moveX
//                mDownY = moveY
//            }
//            MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
//                ptr_notifymessage_list_framelayout.setEnabled(true)
//            }
//            else -> {
//            }
//        }
//
//        return super.dispatchTouchEvent(ev)
//    }

    private lateinit var loadingDialogDelete: SureDeleteDialog

    private fun initSwipListView() {
        val creator = SwipeMenuCreator { menu ->
            // TODO Auto-generated method stub
            val deleteItem = SwipeMenuItem(this@NotifyMessageActivity)
            // set item background
            deleteItem.setBackground(ColorDrawable(Color.rgb(0xF9,
                    0x3F, 0x25)))
            deleteItem.setTitle(getString(R.string.delete))
            deleteItem.setTitleColor(Color.WHITE)
            //				// set item width
            deleteItem.setWidth(dp2px(90))
            deleteItem.setTitleSize(18)
            //				// set a icon
            //				deleteItem.setIcon(R.drawable.ic_delete);
            //				deleteItem.setBackground(R.drawable.delete_list_item_bg);
            // add to menu
            menu.addMenuItem(deleteItem)
        }

        lv_notifymessage.setMenuCreator(creator)
        lv_notifymessage.setOnMenuItemClickListener { position, menu, index ->
            when (index) {
                0 -> {
                    //删除设备操作
                    loadingDialogDelete = SureDeleteDialog(this@NotifyMessageActivity, "", getString(R.string.make_sure_delete), getString(R.string.cancel), getString(R.string.ok), 0)
                    loadingDialogDelete.setCanceledOnTouchOutside(false)
                    loadingDialogDelete.show()
                    loadingDialogDelete.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(View.OnClickListener {
                        userPrestener?.By_Message_del(MyApplication.instance!!.loginInfo!!.getUid().toString(), ar!![position].id, this)
                        loadingDialogDelete.dismiss()
                    })
                    loadingDialogDelete.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(View.OnClickListener {
                        loadingDialogDelete.dismiss()
                    })
                }
                1 -> {
                }
            }// delete
            //					delete(item);
            //					mAppList.remove(position);
            //					mAdapter.notifyDataSetChanged();
        }
    }

    private fun dp2px(dp: Int): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(),
                resources.displayMetrics).toInt()
    }

    override fun onResume() {
        super.onResume()
        query()
    }

    fun query() {
        userPrestener!!.By_Message_query(MyApplication.instance!!.loginInfo!!.getUid().toString(), -1, pageIndex, 20, this)
    }

    override fun onClick(p0: View?) {
        when (p0) {
            iv_actionbar_left -> {
                finish()
            }
            else -> {
            }
        }

    }

}
